<template>
  <el-dialog
    :visible.sync="visible"
    :title="dataForm.details ? '详情' : !dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'"
      :disabled="disabled"
    >
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <ren-select
              v-model="dataForm.type"
              dict-type="banner_type"
              placeholder="请选择"
              style="width: 100%"
            ></ren-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="内容模块" prop="contentType">
            <ren-select
              v-model="dataForm.contentType"
              dict-type="applet_content_type"
              placeholder="请选择"
              style="width: 100%"
            ></ren-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="dataForm.sort" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item  label="开始结束时间" prop="time">
            <el-date-picker
              :picker-options="pickerOptions"
              v-model="value1"
              type="daterange"
              :clearable="false"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片参数：" prop="bannerList" class="picDiv">
            <div class="item">
              <span
                >图片<span style="color: #c0c4cc"
                  >(建议尺寸{{ sizes[dataForm.type-1] }})</span
                ></span
              >
              <span>类型</span>
              <span>排序</span>
              <span>跳转链接</span>
              <span></span>
            </div>

            <div
              class="item"
              v-for="(item, index) in dataForm.bannerList"
              :key="index"
            >
              <el-upload
                class="avatar-uploader"
                :action="url"
                :show-file-list="false"
                :on-success="
                  (res, file, fileList) =>
                    successHandle1(res, file, fileList, index)
                "
                :before-upload="beforeUploadHandle"
              >
                <img v-if="item.path" :src="item.path" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <ren-select
                v-model="item.type"
                dict-type="imgType"
                placeholder="请选择"
                style="width: 100%"
              ></ren-select>
              <el-input v-model="item.sort" placeholder="排序"></el-input>
              <el-input
                v-model="item.linkUri"
                placeholder="链接地址"
              ></el-input>
              <el-button
                type="danger"
                size="mini"
                style="height: 36px"
                @click="delBanner(index)"
                >删除</el-button
              >
            </div>
            <el-button
              type="primary"
              plain
              size="mini"
              @click="addBanner()"
              style="margin: 0 0 30px 30px"
            >
              新增
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer" v-if="!disabled">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
export default {
  data() {
    return {
      visible: false,
      sizes:[
          "750*400px",
          "750*274px",
           "750*420px",
          "750*420px",
          "750*610px",
          "750*420px",
          "702*380px",
          "750*320px",
          "750*320px",
          "750*580px",
          "750*450px",
          "750*450px",
          "750*450px",
          "750*450px",
          "750*450px",
          "750*450px",
          "750*450px",
          "750*970px",
          "522*738px",
          "750*420px",
          "750*500px",
          "750*801px"
        ],
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      fileList: [],
      dataForm: {
        bannerList: [
          {
            type: "",
            linkUri: "",
            path: "",
            sort: "",
          },
        ],
        id: "",
        name: "",
        type: "",
        contentType: "",
        sort: "",
        startDate:"",
        endDate:""
      },
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate = minDate.getTime();
          if (maxDate && maxDate.getTime() > new Date().getTime()) {
            this.choiceDate = "";
          }
        },
        // disabledDate: (time) => {
        //   const today = new Date();
        //   const one = 90 * 24 * 3600 * 1000; // 30天
        //   today.setHours(0, 0, 0, 0);
        //   const maxTime =
        //     today.getTime() > this.choiceDate + one
        //       ? this.choiceDate + one
        //       : today.getTime();
        //   if (this.choiceDate) {
        //     const minTime = this.choiceDate - one;
        //     return time.getTime() < minTime || time.getTime() > maxTime;
        //   }
        //   return time.getTime() > maxTime;
        // },
      },
      value1: [],
    };
  },
  props: {
    disabled: Boolean,
  },

  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {
    value1(newval, oldval) {
      if (newval != oldval&&newval) {
        this.dataForm.startDate = newval[0];
        this.dataForm.endDate = newval[1];
      } else {
        this.dataForm.startDate = "";
        this.dataForm.endDate = "";
      }
    },
  },
  methods: {
    // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
    },
    // 上传成功
    successHandle1(res, file, fileList, index) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      console.log(index);
      this.dataForm.bannerList[index].path = res.data.url;
      console.log(this.dataForm.bannerList[index]);
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    addBanner() {
      this.dataForm.bannerList.push({
        linkUri: "",
        path: "",
        sort: "",
        type: "",
      });
    },
    delBanner(index) {
      this.dataForm.bannerList.splice(index, 1);
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/sys/isappletpic/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          if(this.dataForm.startDate && this.dataForm.endDate){
            this.value1 = [this.dataForm.startDate, this.dataForm.endDate];
          }else{
            this.value1 = ""
          }
          
          console.log(this.value1)
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.dataForm.pathList=this.dataForm.pathList?this.dataForm.pathList:[];
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/sys/isappletpic/",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style scoped lang="scss">
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    .el-upload:hover {
      border-color: #409eff;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 140px;
    height: 140px;
    line-height: 140px;
    text-align: center;
  }

  .avatar {
    width: 140px;
    height: 140px;
    display: block;
  }

  .el-upload-list__item {
    width: 140px;
    height: 140px;
  }

  .el-upload.el-upload--picture-card {
    width: 140px;
    height: 140px;
    line-height: 140px;
  }
}

.picDiv {
  .el-form-item__content {
    .item {
      text-align: center;
      display: grid;
      grid-template-columns: 200px auto auto auto 50px;
      gap: 0 14px;
    }
  }
}
</style>
